//
//  EAGLView.m
//  iDemo
//
//  Created by Dr.Watson on 29/05/08.
//  Copyright Passionfools Design 2008. All rights reserved.
//



#import <QuartzCore/QuartzCore.h>
#import <OpenGLES/EAGLDrawable.h>

#import "EAGLView.h"
#import "Texture2D.h"
#import "LDSprite.h"
#import "LDSpriteLayer.h"
#import "LDSpritesheet.h"
#import "LDSound.h"
#import "SFBattlefield.h"

// #import "LDText.h"

#define USE_DEPTH_BUFFER 0

// A class extension to declare private methods
@interface EAGLView ()

//@property (nonatomic, retain) EAGLContext *context;
@property (nonatomic, assign) NSTimer *animationTimer;

- (BOOL) createFramebuffer;
- (void) destroyFramebuffer;

@end


@implementation EAGLView

//@synthesize context;
@synthesize animationTimer;
@synthesize animationInterval;

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
	UITouch *touch = [touches anyObject]; 
	CGPoint xy;
	
	xy = [touch locationInView: self];
	
//	[testSound rewindAndPlay];
//	touchXY = xy;
//	[battlefield attack : xy];

}

- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {

	UITouch *touch = [touches anyObject]; 
	CGPoint xy;
	
	xy = [touch locationInView: self];
	
//	[battlefield checkAttack];
	[battlefield attack : xy];
}

- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event {
	UITouch *touch = [touches anyObject]; 
	CGPoint xy;
	
	xy = [touch locationInView: self];
	
//	[battlefield attack : xy];
//	[newSprite setStartXY:[newSprite nowX]:[newSprite nowY]];
//	[newSprite setEndXY:xy.x:xy.y];

//	[newSprite calcDistantRatio];

//	[battlefield attack : xy];
//	[testSound rewindAndPlay];
}

// You must implement this
+ (Class)layerClass {
	return [CAEAGLLayer class];
}

- (id)initWithFrame:(CGRect)frame {
    if (self = [super initWithFrame:frame]) {
		// Get the layer
		CAEAGLLayer* eaglLayer = (CAEAGLLayer*) super.layer;
		eaglLayer.opaque = YES;
		
		eaglLayer.drawableProperties =	[NSDictionary dictionaryWithObjectsAndKeys:
										[NSNumber numberWithBool:FALSE], 
										kEAGLDrawablePropertyRetainedBacking, 
										kEAGLColorFormatRGBA8,
										kEAGLDrawablePropertyColorFormat,
										nil];
		
		context = [[EAGLContext alloc] initWithAPI:kEAGLRenderingAPIOpenGLES1];
		if (!context || ![EAGLContext setCurrentContext:context]) {
			[self release];
			return nil;
		}
		[self layoutSubviews];	
		animationInterval = 1.0 / 60.0;
		
		// 建立一個儲存所有texture的array
		spritesheet01 = [[LDSpritesheet alloc] init];
		textureArray = [spritesheet01 loadWithDescriptionFile:@"spritesheet"];
		[spritesheet01 release];
		
		// 載入invaders sprite，作為種子用
		invadersSeedLayer = [[LDSpriteLayer alloc] init];
		[invadersSeedLayer loadSpriteWithDescriptionFile: @"invaders": textureArray];
		
		//載入cursor sprite
		cursorLayer = [[LDSpriteLayer alloc] init];
		[cursorLayer loadSpriteWithDescriptionFile: @"cursor": textureArray];
		
		// 建立新的戰場
		battlefield = [[SFBattlefield alloc] init];
		// 告訴新的戰場，使用那一張invaders sprite sheet作種子用
		[battlefield setInvadersSprite: invadersSeedLayer];
		[battlefield setCursorSprite:	cursorLayer];
		[battlefield newLevel : 0];
		
		// 建立新的layer
		layer01 = [[LDSpriteLayer alloc] init];
		// 用description file將sprites載入到layer
		[layer01 loadSpriteWithDescriptionFile:@"sprite": textureArray];
		
		// also load test sound
		testSound = [[AVAudioPlayer alloc] initWithWav:@"Clunk287"];
		[testSound prepareToPlay];	
		
		CGRect tFrame = CGRectMake(100.0, 50.0, 200.0, 40.0);
		textBox = [[UITextView alloc] initWithFrame:tFrame];
		textBox.editable		= NO;
		textBox.backgroundColor = [UIColor clearColor];
		textBox.textColor		= [UIColor whiteColor];
		textBox.scrollEnabled	= NO;
		[self addSubview:textBox];
		
//		[textBox resignFirstResponder];
//		[self becomeFirstResponder];
		
/*		if ([textBox canResignFirstResponder] == YES) {
			
			[textBox resignFirstResponder] == YES;
			if ([self canBecomeFirstResponder] == YES)char targetStr[256];
		sprintf(targetStr,"%d - %d",[battlefield target01],[battlefield target02]);
		textBox.text = [NSString stringWithCString:targetStr encoding:NSUTF8StringEncoding];
				textBox.text = @"YES";
			else
				textBox.text = @"NO";
			
		}
		else
			textBox.text = @"canNot be first";
	*/	
		//[self becomeFirstResponder];
		//[textBox resignFirstResponder];
		
		
//		textBox = [[LDText alloc] initWithFrame : tFrame];
		
//		[self addSubview:textBox];
	}
	return self;
}

- (void) beginDraw {
	[EAGLContext setCurrentContext:context];
	
	glBindFramebufferOES(GL_FRAMEBUFFER_OES, viewFramebuffer);
	
	glClear(GL_COLOR_BUFFER_BIT);
	
	glColor4f(1.0f, 1.0f, 1.0f, 1.0f);
}

- (void) endDraw {
	glBindRenderbufferOES(GL_RENDERBUFFER_OES, viewRenderbuffer);
	[context presentRenderbuffer:GL_RENDERBUFFER_OES];
}

- (void)drawView {
	
	NSAutoreleasePool *apool = [[NSAutoreleasePool alloc] init];
	
/*	char targetStr[256];
	sprintf(targetStr,"(%d) - (%d), <%d> <%d>",[battlefield target01],[battlefield target02],
		[battlefield cursorX], [battlefield cursorY]);
	textBox.text = [NSString stringWithCString:targetStr encoding:NSUTF8StringEncoding];
*/
	
	// render整個layer
	[self beginDraw];

	[layer01 animate];
	[battlefield animate];
	if ([battlefield isSuccess] == YES) {
		LDSprite *tmpSprite = [layer01 spriteUseKey : "success"];
	//	LDSprite *tmpSprite = [layer01 spriteAtIndex : 7];
		if ([tmpSprite drawMe] == NO) {
			[tmpSprite setNowXY : [tmpSprite startX] : [tmpSprite startY]];
			[tmpSprite calcDistantRatio];
			[tmpSprite setDrawMe : YES];
		}
	}
	
	[self endDraw];

	[apool release];
	
}

// 這實際是initialize opengl的method，只是保留了原來SDK自動執行時的名字
// toolchain是不會自動執行的，所以要手動執行
- (void)layoutSubviews 
{
	[EAGLContext setCurrentContext:context];
	[self destroyFramebuffer];
	[self createFramebuffer];
	
	glViewport(0, 0, backingWidth, backingHeight);
	
	glMatrixMode(GL_PROJECTION);
	glLoadIdentity();
	glOrthof(0, (float)backingWidth, 0, (float)backingHeight, 0, 100);
	
	glMatrixMode(GL_MODELVIEW);
	glLoadIdentity();
	
	glEnable(GL_TEXTURE_2D);
	glEnable(GL_BLEND);
	glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
	
	glEnableClientState (GL_VERTEX_ARRAY);
    glEnableClientState (GL_TEXTURE_COORD_ARRAY);
	
	glClearColor(0.0f, 0.0f, 0.0f, 1.0f);
	
	//	[self drawView];
}


- (BOOL)createFramebuffer {
	
	glGenFramebuffersOES(1, &viewFramebuffer);
	glGenRenderbuffersOES(1, &viewRenderbuffer);
	
	glBindFramebufferOES(GL_FRAMEBUFFER_OES, viewFramebuffer);
	glBindRenderbufferOES(GL_RENDERBUFFER_OES, viewRenderbuffer);
	[context renderbufferStorage:GL_RENDERBUFFER_OES fromDrawable:(CAEAGLLayer*)self.layer];
	glFramebufferRenderbufferOES(GL_FRAMEBUFFER_OES, GL_COLOR_ATTACHMENT0_OES, GL_RENDERBUFFER_OES, viewRenderbuffer);
	
	glGetRenderbufferParameterivOES(GL_RENDERBUFFER_OES, GL_RENDERBUFFER_WIDTH_OES, &backingWidth);
	glGetRenderbufferParameterivOES(GL_RENDERBUFFER_OES, GL_RENDERBUFFER_HEIGHT_OES, &backingHeight);
	
	if (USE_DEPTH_BUFFER) {
		glGenRenderbuffersOES(1, &depthRenderbuffer);
		glBindRenderbufferOES(GL_RENDERBUFFER_OES, depthRenderbuffer);
		glRenderbufferStorageOES(GL_RENDERBUFFER_OES, GL_DEPTH_COMPONENT16_OES, backingWidth, backingHeight);
		glFramebufferRenderbufferOES(GL_FRAMEBUFFER_OES, GL_DEPTH_ATTACHMENT_OES, GL_RENDERBUFFER_OES, depthRenderbuffer);
	}
	
	if(glCheckFramebufferStatusOES(GL_FRAMEBUFFER_OES) != GL_FRAMEBUFFER_COMPLETE_OES) {
		NSLog(@"failed to make complete framebuffer object %x", glCheckFramebufferStatusOES(GL_FRAMEBUFFER_OES));
		return NO;
	}
	
	return YES;
}


- (void)destroyFramebuffer {
	
	glDeleteFramebuffersOES(1, &viewFramebuffer);
	viewFramebuffer = 0;
	glDeleteRenderbuffersOES(1, &viewRenderbuffer);
	viewRenderbuffer = 0;
	
	if(depthRenderbuffer) {
		glDeleteRenderbuffersOES(1, &depthRenderbuffer);
		depthRenderbuffer = 0;
	}
}

- (void)startAnimation {
	self.animationTimer = [NSTimer scheduledTimerWithTimeInterval:animationInterval 
														   target:self 
														 selector:@selector(drawView) 
														 userInfo:nil 
														  repeats:YES];
}

- (void)stopAnimation {
	self.animationTimer = nil;
}

- (void)setAnimationTimer:(NSTimer *)newTimer {
	[animationTimer invalidate];
	animationTimer = newTimer;
}

- (void)setAnimationInterval:(NSTimeInterval)interval {
	
	animationInterval = interval;
	if (animationTimer) {
		[self stopAnimation];
		[self startAnimation];
	}
}

- (void)dealloc {
	
	[self stopAnimation];
	
	if ([EAGLContext currentContext] == context) {
		[EAGLContext setCurrentContext:nil];
	}

	[textureArray release];
	[invadersSeedLayer release];
	[cursorLayer release];
	[battlefield release];
	[layer01 release];
	[context release];
	
	[testSound release];
	[textBox release];
	
	[super dealloc];
}

@end
